import { sha256_digest } from '@/utils/sha256';
import axios from 'axios';
function getFileBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader: FileReader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
      if (e.target) {
        const res = (e.target.result + '').split(',')[1];
        // 转换已经完成
        resolve(res);
      } else {
        reject(new Error('error'));
      }
    };
  });
}
export const uploadToGithub = async (
  filename: string,
  file: File | string
): Promise<{ img: string }[] | [null, { img: string }]> => {
  // const date: Date = new Date();
  const splitArr = filename.split('.');
  const suffix = '.' + splitArr[splitArr.length - 1];
  let fileBase64;
  let filenameSha256: string;
  if (typeof file !== 'string') {
    fileBase64 = await getFileBase64(file);
    filenameSha256 = sha256_digest(fileBase64);
  } else {
    fileBase64 = file;
  }
  // filename = changeHash(fileBase64); // 16位/32位 当前的图片名字
  // filename =
  //   date.getFullYear() +
  //   '' +
  //   (date.getMonth() + 1) +
  //   date.getDate() +
  //   date.getHours() +
  //   date.getMinutes() +
  //   date.getSeconds() +
  //   date.getMilliseconds() +
  //   suffix;
  filenameSha256 += suffix;
  const URL = `https://api.github.com/repos/IceRain-mvc/cdn/contents/exam_project/${filenameSha256}`;
  // request 请求实例
  console.log(filenameSha256);
  return axios
    .request({
      url: URL,
      method: 'put',
      headers: {
        Accept: 'application/vnd.github.v3+json',
        Authorization: 'token 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',
      },
      data: {
        message: 'upload',
        committer: {
          name: 'IceRain-mvc',
          email: '1459574275@qq.com',
        },
        content: fileBase64,
      },
    })
    .then((data) => {
      return [
        null,
        {
          img: 'https://cdn.jsdelivr.net/gh/IceRain-mvc/cdn/exam_project/' + data.data.content.name,
        },
      ];
    })
    .catch((err) => {
      const cdnBaseUrl = 'https://cdn.jsdelivr.net/gh/IceRain-mvc/cdn/exam_project/';
      return [err, { img: cdnBaseUrl + filenameSha256 }];
    });
};
